#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int add = 0;
    add = l1->val + l2->val;
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* prev = newNode;
    struct ListNode* ReNext = newNode;
    newNode->val = add % 10;
    newNode->next = NULL;
    add /= 10;

    l1 = l1->next;
    l2 = l2->next;
    while (l1 && l2)
    {
        add += l1->val + l2->val;
        newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = add % 10;
        newNode->next = NULL;
        prev->next = newNode;
        prev = newNode;

        l1 = l1->next;
        l2 = l2->next;

        add /= 10;
    }
    while (l1 || l2)
    {
        if (l1)
        {
            add += l1->val;
            l1 = l1->next;
        }
        else
        {
            add += l2->val;
            l2 = l2->next;
        }
        newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = add % 10;
        newNode->next = NULL;
        prev->next = newNode;
        prev = newNode;

        add /= 10;
    }
    if (add)
    {
        newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = add % 10;
        newNode->next = NULL;
        prev->next = newNode;
    }


    return ReNext;
}